<?php
session_start();
include_once("common/dbConnect.php");
include_once("header.php");
$handle = db_connect();
if(!$handle){
    echo "Did not access to the database";
    exit();
}

//分页
if(isset($_GET['page'])){
    $pageIndex= intval($_GET['page']);
}
else {
    $pageIndex=1;
}

//总记录数
$sql = "select count(*) from Student";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$totalCount = $row[0];

$pageSize=5;//每页的记录数
$pageCount = ceil($totalCount/$pageSize); //总页数
?>
<script type="text/javascript">
    //删除
    function del(id){
        if (false == confirm('确定要删除吗?'))
            return;

        var data = {};
        data.id = id;
        $.ajax({
            type: "POST",
            url: 'del.php',
            data: data,
            success: function (response) {
                if (response == 'success')
                    window.location.href = 'index.php';
            }
        });
    }
</script>
<div class="container body-content">
<h2>StudentList</h2>
<p><a href="add.php">Create New</a></p>
<table class="table">
<tr>
        <th>Name</th>
        <th>Tel</th>
        <th>Age</th>
        <th>Operation</th>
      </tr>
<?php
// region 列表
if($totalCount>0){
    $student_sql="select * from Student limit ".($pageIndex-1)*($pageSize).",$pageSize";
    $student_result=mysql_query($student_sql);
    while($student=mysql_fetch_assoc($student_result)){
        echo "
        <tr>
            <td>{$student['StudentName']}</td>
            <td>{$student['StudentTel']}</td>
            <td>{$student['StudentAge']}</td>
            <td>
                <a href='edit.php?id={$student['StudentID']}'>Edit</a> |
                <a href='details.php?id={$student['StudentID']}'>Details</a> |
                <a href='javascript:del({$student['StudentID']})'>Delete</a>
            </td>
        </tr>
    ";
    }
}
#endregion
?>
</table>
<?php
//region  翻页信息
if($pageIndex>$pageCount|$pageIndex==0){
    echo "没有此页！";
    exit();
}
$pageSplit = '';
if($pageIndex==1){
    $pageSplit .= '第一页 | 上一页 ';
}
else{
    $pageSplit .= '<a href="index.php?page=1">第一页</a> | <a href="index.php?page='.($pageIndex-1).'">上一页</a> | ';
}
if($pageIndex==$pageCount||$pageCount==0){
    $pageSplit .= ' 下一页 | 尾页';
}
else{
    $pageSplit .=  '<a href="index.php?page='.($pageIndex+1).'">下一 页</a> | <a href="index.php?page='.$pageCount.'">尾页</a>';
}
//输出翻页信息
echo '共'.$totalCount.'条记录，每页'.$pageSize.'条，共'.$pageCount.'页　';
echo $pageSplit;
//endregion
?>
</div>
